package com.toune.villager.activity

import android.os.Bundle
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.toune.dltools.DLSnackbarUtils
import com.toune.dltools.http.GsonBinder
import com.toune.dltools.ui.DLBaseActivity
import com.toune.villager.R
import com.toune.villager.adapter.BookAdapter
import com.toune.villager.model.BookModel
import com.zia.easybookmodule.bean.Book
import com.zia.easybookmodule.engine.EasyBook
import com.zia.easybookmodule.rx.Disposable
import com.zia.easybookmodule.rx.StepSubscriber
import kotlinx.android.synthetic.main.activity_book.*
import java.lang.Exception

class BookActivity : DLBaseActivity<BookModel>() {
    override val layout: Int
        get() = R.layout.activity_book
    override val titleStr: String?
        get() = "书城"

    override fun init(savedInstanceState: Bundle?) {
        mSearchView.onActionViewExpanded()
        //设置是否显示搜索框展开时的提交按钮
        mSearchView.isSubmitButtonEnabled = true;
        //设置输入框提示语
        mSearchView.queryHint = "请输入书籍名称";
        mSearchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                searchStr = query!!
                mViewModel.searchBook(searchStr)
                return true
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                return true
            }

        })
        mViewModel.books.observe(this, {
            setAdapter(it as MutableList<Book>)
        })
    }

    var searchStr = ""
    var bookAdapter: BookAdapter? = null
    val books: MutableList<Book> = ArrayList()
    fun setAdapter(mBooks: MutableList<Book>) {
        mRefreshLv.isRefreshing = false
        hideLoading()
        books.clear()
        books.addAll(mBooks)
        if (bookAdapter == null) {
            bookAdapter = BookAdapter(R.layout.adapter_book, books)
            mRclView.setHasFixedSize(true);
            mRclView.layoutManager =
                StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL)
            mRclView.adapter = bookAdapter
            bookAdapter!!.setOnItemClickListener { adapter, view, position ->
                var bundle = Bundle()
                bundle.putString("book",GsonBinder.toJsonStr(books[position]))
                startToActivity(CatalogActivity::class.java,bundle)
            }
            bookAdapter!!.setEmptyView(R.layout.layout_empty)
        } else {
            bookAdapter!!.notifyDataSetChanged()
        }
    }

    override fun initEventAndData() {
        mRefreshLv.setOnRefreshListener {
            mViewModel.searchBook(searchStr)
        }
    }
}